package com.roy.sms.dao;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.roy.sms.model.Article;
import com.roy.sms.model.Column;

@Repository
public class ArticleDao {

	@Resource
	private SessionFactory sessionFactory;
	
	private Session getSession(){
		return sessionFactory.getCurrentSession();
	}
	
	public void add(Article article){
		getSession().save(article);
	}
	
	public void update(Article article){
		getSession().update(article);
	}
	
	public void delete(int id){
		getSession().delete(load(id));
	}

	public Article load(int id) {
		return (Article) getSession().load(Article.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public List<Article> list(int rowBeginIndex, int rowCount){
		return getSession().createQuery("from Article")
				.setFirstResult(rowBeginIndex)
				.setMaxResults(rowCount).list();
	}
	
	public int getTotal(){
		Long total = (Long) getSession().createQuery("select count(a) from Article a").uniqueResult();
		return total.intValue(); 
	}
	
	public void updateState(int state, int id){
		Article art = load(id);
		art.setState(state);
		getSession().save(art);
	}
	
	@SuppressWarnings("unchecked")
	public List<Article> list(Column column, int rowBeginIndex, int rowCount){
		return getSession().createQuery("from Article a where a.column=?")
		.setParameter(0, column)
		.setFirstResult(rowBeginIndex)
		.setMaxResults(rowCount).list();
	}
	
	public int getTotal(Column column){
		Long t = (Long) getSession().createQuery("select count(a) from Article a where a.column=?")
				.setParameter(0, column).uniqueResult();
		return t.intValue();
	}
	
}
